﻿using System;
using QuickTest.Core.Compilation;
using QuickTest.Core.Events;
using QuickTest.Core.ServiceInterfaces;
using QuickTest.Core.TestRunner;
using QuickTest.Core.Threading;
using QuickTest.Services.Packaging;
using QuickTest.Services.TextRetrieval;

namespace QuickTest.Services.TestRunner
{
    public class TestRunnerService : ITestRunnerService
    {
        private readonly IThreadingProvider threadingProvider;
        private readonly IEventHub eventHub;

        public TestRunnerService()
            : this(new NoThreadingProvider(), new EventHub())
        {
        }

        public TestRunnerService(IThreadingProvider threadingProvider, IEventHub eventHub)
        {
            this.threadingProvider = threadingProvider;
            this.eventHub = eventHub;
        }

        public void RunTests(IRunsTests testRunner, string solutionPath, string outputDirectory)
        {
            ITestPackageService testPackageService = GetTestPackageService(solutionPath, outputDirectory);

            threadingProvider.DoWork(() => ExecuteTestRun(testPackageService, testRunner, solutionPath));
        }

        private void ExecuteTestRun(ITestPackageService testPackageService, IRunsTests testRunner, string solutionPath)
        {
            eventHub.RaiseTestRunExecuted(EventArgs.Empty);

            var testPackage = testPackageService.CreateTestPackage(solutionPath);
            testRunner.RunTests(new TestLoader(testPackage), eventHub);
        }

        protected virtual ITestPackageService GetTestPackageService(string solutionPath, string outputDirectory)
        {
            return new TestPackageService(
                new FileTextRetriever(new FileUri(solutionPath)),
                new MSBuildCompiler(new CompilerLogger(eventHub)),
                new DirectoryUri(outputDirectory));
        }
    }
}
